package com.kgc.scd.util;
import com.kgc.scd.conntant.WechatPayConstant;
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * Created On : 2022/11/4.
 * <p>
 * Author : #jiangguoqiang
 * <p>
 * Description: 微信支付工具类
 */
@Slf4j
public class WechatPayUtil {
    //随机字符库
    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    //随机数对象
    private static final Random RANDOM = new SecureRandom();
    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    /**
     * @author : Administrator
     * @date   : 2022/11/4
     * @param  : []
     * @return : java.lang.String
     * @description : 生成随机字符串 Nonce Str，支持指定字符串
     */
    public static String generateNonceStr(int length) {
        //限制随机字符串长度
        if (length < 6 || length >32){
            length = 32;
        }
        //根据指定的长度，生成随机字符串
        char[] nonceChars = new char[length];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    /**
     * @author : Administrator
     * @date   : 2022/11/4
     * @param  : []
     * @return : java.lang.String
     * @description : 固定字符串2
     */
    public static String generateNonceStr() {

        return generateNonceStr(32);
    }

    /**
     * @author : Administrator
     * @date   : 2022/11/4
     * @param  : []
     * @return : java.lang.String
     * @description : 生成随机字符串 Nonce Str，使用uuid
     */
    public static String generateNonceStrUUID(int length) {

        return (length < 6 || length >32) ? UUID.randomUUID().toString().replace("-","").substring(0,32)
                : UUID.randomUUID().toString().replace("-","").substring(0,length);
    }

    /**
     * @author : Administrator
     * @date   : 2022/11/4
     * @param  : []
     * @return : java.lang.String
     * @description : 生成一个系统订单号，商户系统内部订单号，要求32个字符内（最少6个字符），只能是数字、大小写字母
     */
    public static String generateTradeOrderNo(){
        //系统内订单鬼册，统一头标识+时间戳+随机序号
        return new StringBuilder(WechatPayConstant.WECHAT_PAY_TRADE_ORDER_NO_PREFIX).append(LocalDateTime.now().format(DateTimeFormatter.ofPattern(WechatPayConstant.WECHAT_PAY_TIME_PATTERN_ALL)))
                .append(generateNonceStr(6)).toString();
    }

    /**
     * @author : Administrator
     * @date   : 2022/11/10
     * @param  : [data, key, signType]
     * @return : java.lang.String
     * @description : 生成签名
     */
    public static String generateSignature(final Map<String, String> data, String key) throws Exception {
        return generateSignature(data, key, WechatPayConstant.WECHAT_PAY_SIGN_TYPE_MD5);
    }

    /**
     * @author : Administrator
     * @date   : 2022/11/10
     * @param  : [data, key, signType]
     * @return : java.lang.String
     * @description : 生成签名
     */
    public static String generateSignature(final Map<String, String> data, String key, String signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(WechatPayConstant.WECHAT_PAY_FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);
        if (WechatPayConstant.WECHAT_PAY_SIGN_TYPE_MD5.equals(signType)) {
            return MD5(sb.toString()).toUpperCase();
        }
        else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }
    /**
     * @author : Administrator
     * @date   : 2022/11/10
     * @param  : [data]
     * @return : java.lang.String
     * @description : 生成MD5
     */
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }
    /**
     * @author : Administrator
     * @date   : 2022/11/10
     * @param  : [data]
     * @return : java.lang.String
     * @description : 将Map转换为xml
     */
    public static String generateMapToXml(Map<String, String> data) throws Exception {
        org.w3c.dom.Document document = WechatPayXmlUtil.newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key: data.keySet()) {
            String value = data.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
        try {
            writer.close();
        }
        catch (Exception ex) {
        }
        return output;
    }
    /**
     * @author : Administrator
     * @date   : 2022/11/11
     * @param  : [strXML]
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @description : xml字符串转换为Map
     */
    public static Map<String, String> generateXmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilder documentBuilder = WechatPayXmlUtil.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
            log.warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            throw ex;
        }

    }

    /**
     * @author : Administrator
     * @date   : 2022/11/11
     * @param  : [data, key]
     * @return : boolean
     * @description : 判断签名是否正确，必须包含sign字段，否则返回false。使用MD5签名。
     */
    public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
        return isSignatureValid(data, key, WechatPayConstant.WECHAT_PAY_SIGN_TYPE_MD5);
    }

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。
     *
     * @param data Map类型数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, String> data, String key, String signType) throws Exception {
        if (!data.containsKey(WechatPayConstant.WECHAT_PAY_FIELD_SIGN) ) {
            return false;
        }
        String sign = data.get(WechatPayConstant.WECHAT_PAY_FIELD_SIGN);
        return generateSignature(data, key, signType).equals(sign);
    }
}
